DECLARE @xml XML

SET @xml = 
(
    SELECT
        DocumentId        = ISNULL(DocumentId,0)
    ,   Title             = CAST('<![CDATA[' + ISNULL(Title,'') + ']]>' AS xml)
    ,   DocumentShortName = CAST('<![CDATA[' + ISNULL(DocumentShortName,'') + ']]>' AS xml)
    ,   FileName          = CAST('<![CDATA[' + ISNULL(FileName,'') + ']]>' AS xml)
    ,   Path              = CAST('<![CDATA[' + ISNULL(Path,'') + ']]>' AS xml)
    ,   CreateDate        = ISNULL(Core.dbo.fDateFormat(@GlobalDateFormat,CreateDate),'')
    ,   ModificationDate  = Core.dbo.fDateFormat(@GlobalDateFormat,GETDATE())
    ,   TemplateId        = ISNULL(CAST(TemplateId AS varchar(16)),'')
    ,   IsRoot            = ISNULL(IsRoot,0)
    ,   IsActive          = ISNULL(IsActive,0)
    ,   SortOrdinal       = ISNULL(CAST(SortOrdinal AS varchar(16)),'')
    ,   ClientId          = ISNULL(ClientId,'')
    ,   Tag               = CAST('<![CDATA[' + ISNULL(Tag,'') + ']]>' AS xml)
    FROM
        [Document]
    WHERE
        DocumentId IN
        (
            SELECT
                DocumentId
            FROM
                SegmentDocument
            WHERE
            (
                    SegmentDocument.SegmentId = @SegmentId
                OR
                    dbo.fSegmentIsChildOf(SegmentDocument.SegmentId, dbo.fGetSegmentName(@SegmentId)) = 1
            )
            AND
                SegmentDocument.DocumentId = [Document].DocumentId
        )
    OR
        DocumentId IN
        (
            SELECT
                DocumentId
            FROM
                Document
            WHERE
            (
                    Document.SegmentId = @SegmentId
                OR
                    dbo.fSegmentIsChildOf(Document.SegmentId, dbo.fGetSegmentName(@SegmentId)) = 1
            )
            AND
                Document.DocumentId = [Document].DocumentId
        )
    
    FOR XML AUTO, ELEMENTS, ROOT('ChildDocuments')
)

SELECT @xml
